/* Groups */
(function(package){
    
    var Groups = function ()
    {
        this.studentsSelector = new package.Groups.StudentsSelector($("#students-selector"));
    };
    
    package.Groups = Groups;

}(Sai));


/* StudentsSelector */
(function(package){
    
    var StudentsSelector = function (container)
    {
        this.container      = container;
        this.allList        = new package.StudentsSelector.AllList(container.find("div.all-students"));
        this.selectedList   = new package.StudentsSelector.SelectedList(container.find("div.selected-students"));
        //console.log(this.allList.getSelected());
        
        this.allList.addEventListener(StudentsSelector.AllList.SELECT, $.proxy(this.onAllListSelectStudent, this));
        this.allList.addEventListener(StudentsSelector.AllList.UNSELECT, $.proxy(this.onAllListUnSelectStudent, this));
        
        this.selectedList.addEventListener(StudentsSelector.SelectedList.REMOVE, $.proxy(this.onRemoveStudent, this));
        
        var initiallySelected = this.allList.getSelected();
        
        for(var i=0; i < initiallySelected.length; i++){
            this.allList.select(initiallySelected[i]);
        }
    };

    StudentsSelector.fn = StudentsSelector.prototype;

    StudentsSelector.fn.onAllListSelectStudent = function (event)
    {
        this.selectedList.add(event.id, event.image, event.name);
    };

    StudentsSelector.fn.onAllListUnSelectStudent = function (event)
    {
        this.selectedList.remove(event.id, event.image, event.name);
    }

    StudentsSelector.fn.onRemoveStudent = function (event)
    {
        //console.log("onRemoveStudent"+event.id);
        this.allList.unselect(event.id);
    };
    
    package.StudentsSelector = StudentsSelector;

}(Sai.Groups));


/* AllList */
(function(package){
    
    var AllList = function (container)
    {
        this.container  = container;
        this.search     = new AllList.Search(container.find("div.search"));
        this.filters    = new AllList.Filters(container.find("div.filters"));
        this.list       = container.find("div.form-fields");
        this.noResults  = this.list.find("div.no-students-msg");
        
        this.search.addEventListener(AllList.Search.CHANGE, $.proxy(this.onSearchChange, this));
        this.filters.addEventListener(AllList.Filters.CHANGE, $.proxy(this.onFiltersChange, this));
        this.list.find("input").change($.proxy(this.onInputChange, this));
    };
    AllList.fn = AllList.prototype;

    AllList.fn.select = function (id)
    {
        console.log("select " +id);
        var item = this.list.find("input[value='" + id + "']").parent();
            item.find("input").attr("checked", "true");
            item.addClass("selected");
        
        var data = this.getItemData(item);
        
        this.dispatchEvent({ type:AllList.SELECT, id:data.id, image:data.image, name:data.name });
    };
    
    AllList.fn.unselect = function (id)
    {
        var item = this.list.find("input[value='" + id + "']").parent();
            item.find("input").removeAttr("checked");
            item.removeClass("selected");
        
        var data = this.getItemData(item);
        
        this.dispatchEvent({ type:AllList.UNSELECT, id:data.id, image:data.image, name:data.name });
    };

    AllList.fn.getSelected = function ()
    {
        var selectedInpus = this.list.find("input:checked");
        var selected        = [];
        
        for(var i=0; i < selectedInpus.length; i++){
            selected.push($(selectedInpus[i]).val());
        }
        return selected
    };
    
    AllList.fn.filter = function (text, state)
    {
        //console.log("AllList - text:"+text+" - state:"+state);
        this.list.children().hide();
        this.list.children().filter(function(index)
        {
            if(text && state)
            {
                if($(this).find("span").text().toLowerCase().indexOf(text.toLowerCase()) != -1 &&
                   $(this).find("input").data("filter") == state)
                {
                    return $(this);
                }
            }
            else if(text && !state)
            {
                if($(this).find("span").text().toLowerCase().indexOf(text.toLowerCase()) != -1)
                {
                    return $(this);
                }
            }
            else if(!text && state)
            {
                if($(this).find("input").data("filter") == state)
                {
                    return $(this);
                }
            }
            else
            {
                return $(this);
            }
        }).show();
        
        if(this.list.children().filter(":visible").length)
        {
            this.noResults.hide();
        }
        else
        {
            this.noResults.css("display","table");
        }
    };
    
    AllList.fn.onInputChange = function (event)
    {
        var item = $(event.currentTarget).parent();
        var data = this.getItemData(item);
        
        if(item.find("input:checked").length)
        {
            item.addClass("selected");
            this.dispatchEvent({ type:AllList.SELECT, id:data.id, image:data.image, name:data.name });
        }
        else
        {
            item.removeClass("selected");
            this.dispatchEvent({ type:AllList.UNSELECT, id:data.id, image:data.image, name:data.name });
        }
    };
    
    AllList.fn.getItemData = function (item)
    {
        var data        = {}
            data.id     = item.find("input").val();
            data.image  = item.find("img").attr("src");
            data.name   = item.find("span").text();
        return data;
    }
    
    AllList.fn.onSearchChange = 
    AllList.fn.onFiltersChange = function (event)
    {
        this.filter(this.search.getText(), this.filters.getSelected());
    };
    
    AllList.SELECT      = "onAllListStudentSelect";
    AllList.UNSELECT    = "onAllListStudentUnSelect";

    EventDispatcher.prototype.apply(AllList.prototype);
    
    package.AllList = AllList;

}(Sai.Groups.StudentsSelector));


/* Search */
(function(package){
    
    var Search = function (container)
    {
        this.container      = container;
        this.input          = container.children("input");
        this.searchIcon     = container.children("span.icon");
        this.clearButton    = container.children("button.clear");
        //console.log(this);
        this.input.keyup($.proxy(this.onInputChange, this));
        this.clearButton.click($.proxy(this.onClearButtonClick, this));
    };
    
    Search.fn = Search.prototype;

    Search.fn.clear = function ()
    {
        this.input.val("");
        this.onInputChange();
    };
    
    Search.fn.getText = function ()
    {
        return this.input.val();
    };
    
    Search.fn.onInputChange = function (event)
    {
        //console.log($(this.input)[0].value);
        if(event && event.keyCode == 27) { // Tecla "ESCAPE"
            this.clear();
        }else{
            if($(this.input)[0].value)
            {
               this.searchIcon.hide(); 
               this.clearButton.show();
            }
            else
            {
               this.searchIcon.show(); 
               this.clearButton.hide();
            }
            this.dispatchEvent({ type:Search.CHANGE });
        }
    };
    
    Search.fn.onClearButtonClick = function (event)
    {
        event.preventDefault();
        this.input.focus();
        this.clear();
    };
    Search.CHANGE = "onSelectChange";
    
    EventDispatcher.prototype.apply(Search.prototype);
    
    package.Search = Search;
    
}(Sai.Groups.StudentsSelector.AllList));


/* Filters */
(function(package){
    
    var Filters = function (container)
    {
        this.container  = container;
        this.buttons    = container.children("button");
        //console.log(this);
        this.buttons.click($.proxy(this.onButtonClick, this));
    };
    
    Filters.fn = Filters.prototype;

    Filters.fn.getSelected = function ()
    {
        return this.buttons.filter(".selected").data("filter");
    };
    
    Filters.fn.onButtonClick = function (event)
    {
        event.preventDefault();
        
        var button = $(event.currentTarget);
        var selected = button.hasClass("selected");
        //console.log(this.buttons.filter(".selected").length);
        
        if(!selected)
        {
            this.dispatchEvent({ type:Filters.CHANGE });
        }
        this.buttons.removeClass("selected");
        
        if(selected)
        {
            button.removeClass("selected");
        }
        else
        {
            button.addClass("selected");
        }
        
        this.dispatchEvent({ type:Filters.CHANGE });
    };
    Filters.CHANGE = "onFiltersChange";
    
    EventDispatcher.prototype.apply(Filters.prototype);
    
    package.Filters = Filters;
    
}(Sai.Groups.StudentsSelector.AllList));


/* SelectedList */
(function(package){
    
    var SelectedList = function (container) {
        this.container  = container;
        this.list       = container.find("div.form-fields");
        this.total      = container.find("strong.title > span.total");
    };
    SelectedList.fn = SelectedList.prototype;

    SelectedList.fn.add = function (id, image, name)
    {
        if(!this.list.find("input[value='" + id + "']").length)
        {
            var item = $([
                '<label class="no-quote">',
                    '<input value="' + id + '" type="checkbox" name="students[]" readonly checked />',
                    '<img src="' + image + '" class="size-32x32" />',
                    '<span class="text">' + name + '</span><button class="button important red">Deseleccionar</button>',
                '</label>'
            ].join(""));

                item.find("button").click($.proxy(this.onClickDeleteBt, this));

            this.list.append(item);
        };
        
        this.updateTotal();
    };

    SelectedList.fn.remove = function (id)
    {
        //console.log(this.list);
        this.list.find("input[value='" + id + "']").parent().remove();
        
        this.updateTotal();
    };

    SelectedList.fn.updateTotal = function ()
    {
        this.total.text(this.list.find("input").length);
    };

    SelectedList.fn.onClickDeleteBt = function (event)
    {
        event.preventDefault();

        var item    = $(event.currentTarget).parent();
        var id      = item.find("input").val();

        this.dispatchEvent({ type:SelectedList.REMOVE, id:id });

        this.remove(id);
    };
    SelectedList.REMOVE = "onRemove";

    EventDispatcher.prototype.apply(SelectedList.prototype);

    package.SelectedList = SelectedList;
    
}(Sai.Groups.StudentsSelector));


$(document).ready(function() {
    new Sai.Groups();
});